// pages/search/search.js
const app = getApp();
const getInf = (str, key) => str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
const common = require("../../utils/common.js")
const url = app.globalData.url;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: app.globalData.url,
    val: '',
    list: [],
    bqs: true,
    oldls: false,
    ssk: false,
    ssl: true,
    mrpno: 1,
    count: 1,
    jzshow: false,
    jzwz: '加载中...',
    imgwk: ``
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (o) {
    this.lisf();
    this.peizi();
    if(o){
      this.setData({val:o.val})
      this.fsqq(1, o.val);
    }
  },
   // 配置文件
   peizi: function () {
    clearTimeout(this.loding_timer);
    let that = this;
    app.fetch('api/wx/getpeizi', { dlx: 'xcxlist' }, "GET", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        wx.setNavigationBarTitle({
          title: "搜索"
        });
        that.setData({ peizi: data.data, loding: false });
        that.hquser();
      } else {
        wx.showModal({
          title: '接口数据错误',
          content: '接口:"' + url + 'api/wx/getpeizi.php' + '",msg:' + data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {

          },
          fail: function (res) { },//接口调用失败的回调函数
          complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
        })
      }
    })
  },
  // 获取user信息;
  hquser() {
    let that = this;
    wx.getStorage({
      key: 'openid',
      success(res) {
        app.fetch('api/wx/user', { openid: res.data }, "POST", (err, data) => {
          if (data.code == 200) {
            that.setData({ user: data.data[0] })
            that.getssfx();
          }
        })
      }
    })
  },
  lisf: function () {
    // console.log(1)
    var that = this;
    var oldls = [];
    wx.getStorage({
      key: 'oldls',
      success(res) {
        console.log(res);
        console.log(res.data.indexOf(','));
        if (res.data.indexOf(',') != -1) {
          oldls = res.data.split(',');
          console.log(oldls);
        } else {
          oldls.push(res.data);
        }
        console.log(oldls);
        that.setData({ oldls: oldls[0] != '' ? oldls : false })
        // console.log(oldls)
      }
    })
  },
  lsss: function (e) {
    // console.log(e.target.dataset.val)
    this.setData({ val: e.target.dataset.val });
    this.fsqq(1, e.target.dataset.val);
    app.fetch('api/wx/addssfx', {txt:e.target.dataset.val,bz:'1'}, "POST", (err, data) => {
      console.log(data)
    })
  },
  inputval: function (e) {
    var that = this;
    // console.log(e.detail.value)
    var val = e.detail.value;
    if (val.substring(val.length - 1, val.length) == " ") {
      that.setData({ val: val.substring(0, val.length - 1),list:[] });
    } else if (val != "") {
      that.setData({ val: val });
      that.fsqq(1, that.data.val);
    }else{
      that.setData({list:[],val:''})
    }
  },
  fsqq: function (pno, val) {
    var that = this;
    that.setData({ list: [] });
    let list = []
    let sj = {
      pno: pno,
      pgs: 10,
      kw: val
    };
    app.fetch('api/wx/getsearch', sj, "POST", (err, data) => {
      console.log(data)
      for (var i = 0; i < data.data.length; i++) {
        if (data.data[i].ewm) {
          data.data[i].ewm = url + data.data[i].ewm;
        }
        data.data[i].title = getInf(data.data[i].title, that.data.val);
        data.data[i].addtime = common.bijiao(data.data[i].addtime);
        if (data.data[i].logolist) {
          var arr = data.data[i].logolist.split(",");
          data.data[i].logolist = [];
          let ls = arr.length < 5 ? arr.length : 5;
          for (let a = 0; a < ls; a++) {
            data.data[i].logolist.push(url +arr[a]);
          }
        } else {
          data.data[i].logolist = [];
          // data[i].imgs.push(data[i].tx);
        };
        list.push(data.data[i]);
        wx.hideLoading();
      }
      that.setData({
        list: list,
        pno: Number(data.pno) + 1,
        pcount: Number(data.pageCount), 
        loding: false 
      });
      if (list == "") {
        that.setData({ ssk: true, ssl: false })
      } else {
        that.setData({ ssl: false, ssk: false })
      }
      if (that.data.val == '') {
        that.lisf();
      }
    })

  },
  detail: function (e) {
    // console.log(e)
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../details/details?id=' + id
    })
  },
  jrlis: function (e) {
    var that = this;
    var val = that.data.val;
    var list=that.data.list;
    var oldls = '';
    if (val != '' && val!='undefined'&&val&&list.length>0) {
      wx.getStorage({
        key: 'oldls',
        success(res) {
          oldls = res.data;
          console.log(oldls);
          if (oldls.indexOf(val) == -1) {
            wx.setStorage({
              key: 'oldls',
              data: oldls ? oldls + ',' + val : val
            })
            that.lisf();
          }
        },
        fail(e) {
          wx.setStorage({
            key: 'oldls',
            data: val
          })
          that.lisf();
        }
      })
      app.fetch('api/wx/addssfx', {txt:val,bz:'1'}, "POST", (err, data) => {
        console.log(data)
        if(data.code==200){
          that.getssfx();
        }
      })
    }
  },
  getssfx(){
    let that=this,list=[];
    app.fetch('api/wx/getssfx', {pno:1,bz:2}, "POST", (err, data) => {
      console.log(data)
      if(data.code==200){
        for(let p of data.list){
          list.push(p)
        }
      }
      app.fetch('api/wx/getssfx', {pno:1,bz:1}, "POST", (err, data) => {
        console.log(data)
        if(data.code==200){
          for(let p of data.list){
            list.push(p)
          }
          that.setData({rmls:list})
        }
      })
    })
  },
  btnqc: function () {
    wx.setStorage({
      key: 'oldls',
      data: ""
    })
    this.onLoad();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    that.setData({ jzshow: true });
    var count = that.data.pcount;
    var pno = that.data.pno;
    if (pno-1 < count) {
      that.fsqq(pno,that.data.val);
    } else {
      that.setData({ jzwz: "已经加载完了" });
      setTimeout(function () {
        that.setData({ jzshow: false });
      }, 1000)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this;
    return {
      title: that.data.val, // 转发后 所显示的title
      path: '/pages/search/search?val=' + that.data.val, // 相对的路径
      // imageUrl: that.data.url + that.data.list.imgs[0],
      success: (res) => {    // 成功后要做的事情
        // console.log(res.shareTickets[0])
        // console.log
      },
      fail: function (res) {
        // 分享失败
        // console.log(res)
      }
    }
  },
  onShareTimeline(){
    let that=this;
    return {
      title: that.data.val,
      query:'/pages/search/search?val=' + that.data.val, // 相对的路径
    }
  }
})